<template>
  <div :style="{backgroundColor:`${headerBg}` }" >
    <div class="flex-middle" style="height: 90px;">
      <div class="container tw-relative">
        <div class="font-small flex-between flex-middle" style="font-size: 16px;color: #171920">
          <div class="flex-middle">
            <div style="margin-right: 65px; font-size: 24px" class="click" @click="goHome">
              <img src="@/assets/images/common/head-logo.png" class="tw-h-55" alt="">

            </div>
            <div CLASS="fontFam" v-for="(item, index) in data.tabList" :key="index" @click.stop="tabChange(index)">
              <a class="headerTab" :class="{ active: data.selectedIndex == index, black: data.selectedIndex != 0 }"
                 :style="index == 0 ? 'margin-left: 0' : ''">
                <span class="head-tab-item">{{ item.name }}</span>
              </a>
            </div>
          </div>
          <div v-if="data.showLoginButton" class="flex-middle">
            <el-button class="base-button header-button" style="margin-right: 1px"
                       @click="goLogin('login')">{{ '登录' }}{{ loginShow }}
            </el-button>
            <el-button class="base-button header-button-light" @click="goLogin('register')">{{ '注册' }}
            </el-button>
          </div>
          <div v-else class=" my-admin ">
            <div class=" width100 border-box" :style="{backgroundColor:`${headerBg}`}">
              <div class="flex-between-center tw-p-8 border-box" style="cursor: pointer;box-shadow:none;">
                <p class="flex-middle" style="box-shadow:none;">
                  <img :src="data.userInfo.headerImg"
                       alt="" style="width: 40px;height: 40px;border-radius: 50%;box-shadow:none;">
                  <span
                      style="margin-left: 8px;font-size: 16px;color: #171920;box-shadow:none;">{{
                      data.userInfo.userName
                    }}</span>
                </p>
                <el-icon :size="20" color="#b6bdd1" class="icon-radio">
                  <CaretBottom/>
                </el-icon>

              </div>
              <ul class=" width100  font-normal admin-list click" :style="{backgroundColor:`${headerBg}`}">

                <li command="center" @click="handleCommand('center')">个人中心</li>
                <li command="order" @click="handleCommand('order')">我的订单</li>
                <li command="password" @click="handleCommand('password')">修改密码</li>
                <li command="quit" @click="handleCommand('quit')">退出登录</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive} from 'vue';
import {useRouter} from 'vue-router';
import {useStore} from 'vuex';
import defaultHeaderImage from '@/assets/images/user/default-header.png'
import {ElMessage, ElMessageBox} from 'element-plus'
import {CaretBottom} from '@element-plus/icons-vue'
import {logout} from '../../api/user.js'
import {removeUserInfo} from "../../utils/auth";
import {formatLocalStorageItem} from "../../utils/common.js"

const store = useStore();
let loginShow = store.state.isShowLogin
const router = useRouter();
const {proxy} = getCurrentInstance();
const emits = defineEmits(['tabIndexChange']) // 语法糖
const props = defineProps({
  selectedIndex: {
    type: Number
  },
  headerBg: {
    type: String,
    default:'white'
  },
});
const data = reactive({
  showLoginButton: false,
  selectedIndex: -1,
  userInfo: {
    mobile: '',
    userName: '',
    headerImg: defaultHeaderImage,
  },
  tabList: [
    {name: '首页', dataIndex: 0},
    {name: '课程中心', dataIndex: 1},
    {name: '个人中心', dataIndex: 2},
    {name: '学习中心', dataIndex: 3},
    // {name: '关于我们', dataIndex: 4},
  ],
});
onMounted(() => {
  if (props.selectedIndex >= 0) {
    data.selectedIndex = props.selectedIndex
  }
  data.showLoginButton = !localStorage.getItem('token')
  initUserData()
})
const initUserData = () => {
  data.userInfo.userName = formatLocalStorageItem('name')
  data.userInfo.mobile = formatLocalStorageItem('mobile')
  data.userInfo.headerImg = formatLocalStorageItem('avatarPicUrl') || defaultHeaderImage
}

function tabChange(index) {
  data.selectedIndex = index==4?data.selectedIndex:index
  emits('tabIndexChange', index)
  // router.push({ path: '/', query:{index: data.selectedIndex}})
  if (index == 0) {
    router.push({path: '/'})
  } else if (index == 1) {
    router.push({path: '/course/center'})
  } else if (index == 2) {
    isLogin(() => {
      router.push({path: '/user/index'})
    })
  } else if (index == 3) {
    isLogin(() => {
      router.push({path: '/study/index'})
    })
  }else if (index == 4){
    const {href} = router.resolve({name: 'aboutUs'});
  window.open(href, '_blank');
  }
}
const goHome = () => {
  router.push({path: '/'})
}
const isLogin = (afterHandle) => {
  let token = localStorage.getItem('token')
  if (token) {
    afterHandle()
  } else {
    ElMessageBox.confirm('账号未登录，是否去登录', '系统提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      goLogin('login')
    }).catch(() => {
    });
  }
}

const setSelectedIndex = (index) => {
  data.selectedIndex = index;
}
const userIsLogin = (value) => {
  data.showLoginButton = !localStorage.getItem('token')


  initUserData()
}
//暴露state和play方法
defineExpose({
  setSelectedIndex,
  initUserData,
  userIsLogin
});

const handleCommand = (command) => {
  let commandMap = {
    'center': () => {
      router.push({
        name: 'userCenter',
        query: {
          typeCode: 'info'
        }
      })
    },
    'order': () => {
      router.push({
        name: 'userCenter',
        query: {
          typeCode: 'order'
        }
      })
    },
    'password': () => {
      router.push({
        name: 'userCenter',
        query: {
          typeCode: 'account'
        }
      })
    },
    'quit': () => submitLogout()
  };
  if (commandMap.hasOwnProperty(command)) {
    commandMap[command]();
  }
}

function goLogin(code) {
  router.push({
    path: '/login',
    query: {
      code: code
    }
  })
}

function submitLogout() {
  ElMessageBox.confirm('确认是否退出登录？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    logout({}, () => {
      ElMessage.success('退出成功')
      removeUserInfo()
      data.showLoginButton = true
      goLogin('login')
    })
  }).catch(() => {
  })
}


</script>

<style scoped>
.my-admin {
  min-width: 194px;
  position: absolute;
  right: 0;
  top: -7px;
  z-index: 99;

}
.fontFam{
  font-family: PingFang SC, PingFang SC !important;
}
.admin-list {
  display: none;
  box-shadow: none !important;

  > li {
    padding: 0 8px;
    box-shadow: none !important;
    border-top: 1px solid #ebebeb;
    height: 42px;
    line-height: 41px;
    color: #9598a2;
    text-align: center;
    font-size: 14px;
  }

  > li:hover {
    background: #ebebeb;
  }
}

.my-admin :hover {
  box-shadow: 0 0px 12px 0 rgba(0, 0, 0, .1);
}
.my-admin :hover .icon-radio{
  transform: rotate(180deg);
}
.my-admin :hover .admin-list {
  display: block !important;
}

.headerTab {
  margin-left: 0;
  cursor: pointer;
  padding: 6px 15px;
}

.active,
.headerTab:hover,
.black:hover,
.black.active {
  color: #04ADDB;
  /*background: #DEEFFF;*/
  /*border-radius: 12px;*/
}

.active .head-tab-item,
.headerTab:hover .head-tab-item {
  padding-bottom: 5px;
  border-bottom: solid 3px #04addb;
}

:deep(.el-tooltip__trigger:focus-visible) {
  outline: unset;
}

.base-button {
  padding: 0 30px;
  font-size: 14px;
  border-radius: 28px;
  border: 1px #04addb solid;
  text-align: center;
  align-content: center;
  height: 26px;
}

.header-button, .header-button-light:hover {
  color: white;
  background: #04ADDB;
}

.header-button-light {
  color: #04ADDB;
  background: white;
}

.header-button:hover{
  background: #019DDB;
  border-color: #019DDB;
  color: white;
}

</style>

<style>
.user-dropdown .el-dropdown-menu__item {
  font-family: SHS-CN, serif;
  font-weight: 400;
  font-size: 14px;
  color: #171920;
}
</style>
